const { app, BrowserWindow, ipcMain, Menu, protocol } = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs')
const isDev = process.env.NODE_ENV !== 'production'

// 注册app协议
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let mainWindow

function createWindow() {
  // 设置应用图标路径
  // 在打包后，__dirname 指向 dist_electron，资源文件在 bundled 或 extraResources
  let iconPath
  if (isDev) {
    iconPath = path.join(__dirname, '../public/icon.jpg')
  } else {
    // 尝试多个可能的路径
    const possiblePaths = [
      path.join(__dirname, '../icon.jpg'),
      path.join(__dirname, '../../icon.jpg'),
      path.join(process.resourcesPath, 'icon.jpg'),
      path.join(__dirname, '../public/icon.jpg')
    ]
    iconPath = possiblePaths.find(p => fs.existsSync(p)) || possiblePaths[0]
  }

  mainWindow = new BrowserWindow({
    width: 1400,
    height: 900,
    title: 'InfluxDB Client',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
      devTools: true
    },
    icon: iconPath
  })

  if (isDev) {
    mainWindow.loadURL('http://localhost:8081')
    mainWindow.webContents.openDevTools()
  } else {
    // 使用file://协议加载HTML文件，避免app://协议的问题
    const indexPath = path.join(__dirname, 'index.html')
    mainWindow.loadURL(`file://${indexPath}`)
    // 生产环境下注释掉开发者工具
    // mainWindow.webContents.openDevTools()
  }

  // Hide menu bar
  Menu.setApplicationMenu(null)
  mainWindow.setMenuBarVisibility(false)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.whenReady().then(() => {
  // 注册file协议处理
  protocol.registerFileProtocol('file', (request, callback) => {
    const pathname = decodeURI(request.url.replace('file:///', ''))
    callback(pathname)
  })

  // 注册app协议处理
  protocol.registerFileProtocol('app', (request, callback) => {
    const url = request.url.substr(6) // 去掉 'app://'
    const filePath = path.join(__dirname, url)
    callback({ path: filePath })
  })
  
  createWindow()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

ipcMain.handle('app-version', () => {
  return app.getVersion()
})